package com.morningstar.qs.api.basic.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 * @deprecated
 * @author dchen2
 *
 */
public class XMLFileUtilExt {
	 /*
	 * Write a XML file
	 */
	public static boolean FileWrite(Document document, String file) {
		boolean ret = false;
		FileWriter out = null;
		try {
			out = new FileWriter(file);
			document.write(out);
			ret = true;
		} catch (IOException e) {
			e.printStackTrace();
			ret = false;
		} finally {
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					ret = false;
				}
			}
		}
		return ret;
	}

	/*
	 * Write a XML format file
	 */
	public static boolean XMLWrite(Document document, String file) {
		boolean ret = false;
		XMLWriter writer = null;
		FileWriter out = null;
		try {
			out = new FileWriter(file);
			writer = new XMLWriter(out);
			writer.write(document);
			ret = true;
		} catch (IOException e) {
			e.printStackTrace();
			ret = false;
		} finally {
			if (null != writer) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
					ret = false;
				}
			}
			
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					ret = false;
				}
			}
		}
		return ret;
	}
	
	public static org.w3c.dom.Document XMLReader(String xmlFile) throws Exception {
		org.w3c.dom.Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();   
		DocumentBuilder db = dbf.newDocumentBuilder();   
		doc = db.parse(new File(xmlFile));
		return doc;
	}
	
	public static String xmlDocToString(Document document) {
		String string = "";
		ByteArrayOutputStream out = null;
		XMLWriter writer = null;
		try {
			out = new ByteArrayOutputStream();
			OutputFormat format = new OutputFormat("", true, "UTF-8");
			writer = new XMLWriter(out, format);
			writer.write(document);
			string = out.toString("UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != out) {
					out.close();	
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if (null != writer) {
					writer.close();	
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return string;
	}

	public static Document stringToXmlDoc(String string) {
		Document document = null;
		try {
			document = DocumentHelper.parseText(string);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return document;
	}
}
